package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import DataStorageClasses.Reviewer;
import Database.DatabaseConnector;
import ExceptionClasses.InvalidReviewerAuthenticationException;


/**
 * Servlet implementation class SubscriptionServlet
 */
@WebServlet("/SubscriptionServlet")
public class SubscriptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 HttpSession session = request.getSession();
		 DatabaseConnector db = new DatabaseConnector();
		 
		 System.out.println("in getting subscription servlet");
		 boolean logged = (Boolean) session.getAttribute("subloggedIn");
		 
		 if(logged)
		 {
			String user = (String) session.getAttribute("subUser");
		 	String password = (String) session.getAttribute("subPass");
		 
		 	try {
				Reviewer curr = db.getReviewerInfo(user, password);
				
				String[] subs = curr.getSubscriptions();
				
				JSONObject result = new JSONObject();
				
				JSONArray jArray = new JSONArray();
				System.out.println("getting subs");
				
				try {
					
					for(int i = 0; i < subs.length; i++)
					{
						System.out.println(subs[i]);
						jArray.put(subs[i]);
					}
					
					result.put("SubList", jArray);
					
					response.getWriter().print(result.toString());
					response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
				}
				
			} catch (InvalidReviewerAuthenticationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
			}
		 }
		 else{
			 System.out.println("getSub: no one logged in");
			 response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		 }
	}

}
